package com.krtech.wecard.module.weixin.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.json.GsonParser;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpMenuServiceImpl;
import me.chanjar.weixin.mp.enums.WxMpApiUrl;
import org.springframework.beans.factory.annotation.Autowired;

import static me.chanjar.weixin.mp.enums.WxMpApiUrl.Menu.MENU_ADDCONDITIONAL;
import static me.chanjar.weixin.mp.enums.WxMpApiUrl.Menu.MENU_CREATE;

@Slf4j
public class WxMpMenuServiceImplWecard extends WxMpMenuServiceImpl {

    private WxMpService wxMpService;


    public WxMpMenuServiceImplWecard(WxMpService wxMpService) {
        super(wxMpService);
        this.wxMpService = wxMpService;
    }

    @Override
    public String menuCreate(WxMenu menu) throws WxErrorException {
        String menuJson = menu.toJson();
        WxMpApiUrl.Menu url = MENU_CREATE;
        if (menu.getMatchRule() != null) {
            url = MENU_ADDCONDITIONAL;
        }

        log.info("开始创建菜单：{}", menuJson);

        String result = this.wxMpService.post(url, menuJson);
        log.info("创建菜单：{},结果：{}", menuJson, result);
        log.info("创建菜单结果：{}", result);

        if (menu.getMatchRule() != null) {
            return GsonParser.parse(result).get("menuid").getAsString();
        }

        return null;
    }

}
